//
//  TimeUpListViewController.m
//  TerritoryShopkeeper
//
//  Created by xiaowu on 2017/12/7.
//  Copyright © 2017年 ZDQK. All rights reserved.
//

#import "TimeUpListViewController.h"
#import "TimeUpItemCell.h"
#import "TimeUpTitleView.h"
#import "TimeClockView.h"
#import "GoodsDetailViewController.h"

@interface TimeUpListViewController () <UITableViewDataSource, UITableViewDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tableViewTop;

@property (nonatomic, strong) TimeUpTitleView *titleView;

@property (nonatomic, strong) TimeClockView *timeView;
@property (nonatomic, strong) NSMutableArray<TimeUpTimeItem *> *timeArr;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) NSMutableArray<GoodsListModel *> *tableArray;

@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) NSInteger timerSec;
@end

@implementation TimeUpListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self hiddenShadowImage:NO];
    self.navigationItem.title = @"限时秒杀";
    
    self.page = 1;
    
    [self configureUI];
    [self getNetData];
    
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    self.titleView.frame = CGRectMake(0, 0, ScreenWidth, 50);
    //self.tableView.mj_insetT = 10;
}

#pragma mark - Method
- (void)configureUI {
    [self.view addSubview:self.titleView];
    
    self.view.backgroundColor = [UIColor backgroundColor];
    self.tableView.backgroundColor = [UIColor backgroundColor];
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.emptyDataSetSource = self;
    self.tableView.emptyDataSetDelegate = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"TimeUpItemCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"cell"];
    [self.tableView clearExtendCellLine];
    
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 10)];
    [header setBackgroundColor:[UIColor backgroundColor]];
    self.tableView.tableHeaderView = header;
    
    __block typeof(self) blockSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _page = 1;
        [blockSelf getGoodsNetData];
    }];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _page++;
        [blockSelf getGoodsNetData];
    }];
    [self.tableView.mj_footer setHidden:YES];
}

#pragma mark - 网络请求
- (void)getNetData {
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    __block typeof(self) blockSelf = self;
    [MYAFNetworking POST:URL_Get_Seckill_Time_List parameters:nil success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            [blockSelf.timeArr removeAllObjects];
            NSArray *dataArr = responseObject[@"data"];
            //NSString *nowData = [DateSomeThing getDateStr:[NSDate date] dateFormat:@"HH:mm"];
            
            for (NSDictionary *dic in dataArr) {
                TimeUpTimeItem *model = [TimeUpTimeItem mj_objectWithKeyValues:dic];
                CGFloat startMin = [DateSomeThing getStringWithCurrentTimeStr:model.sktime currentDateFormat:@"HH:mm:ss"];
                if (model.endtime.length > 2) {
                    if ([[model.endtime substringToIndex:2] isEqualToString:@"24"]) {
                        model.endtime = @"23:59:59";
                    }
                }
                CGFloat endMin = [DateSomeThing getStringWithCurrentTimeStr:model.endtime currentDateFormat:@"HH:mm:ss"];
                
                if (startMin >= 0) {
                    model.title = @"即将开始";
                    model.state = 0;
                } else if (startMin < 0 && endMin > 0) {
                    model.title = @"抢购中";
                    model.state = 1;
                } else if (endMin <= 0) {
                    model.title = @"已结束";
                    model.state = -1;
                }
                
                if (model.state >= 0) {
                    [blockSelf.timeArr addObject:model];
                }
            }
            
            if (blockSelf.timeArr.count > 0) {
                TimeUpTimeItem *model = blockSelf.timeArr.firstObject;
                CGFloat sec = 0;
                if (model.state == 1) {
                    sec = [DateSomeThing getStringWithCurrentTimeStr:model.endtime currentDateFormat:@"HH:mm:ss"];
                } else if (model.state == 0) {
                    sec = [DateSomeThing getStringWithCurrentTimeStr:model.sktime currentDateFormat:@"HH:mm:ss"];
                }
                [blockSelf.timeView setTimerForReset:sec];
                blockSelf.timerSec = sec;
                blockSelf.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countdownTimerAction) userInfo:nil repeats:YES];
                
                [blockSelf.titleView setDataSource:blockSelf.timeArr withBlock:^(NSInteger index) {
                    
                    TimeUpTimeItem *model = self.timeArr[index];
                    CGFloat sec = 0;
                    if (model.state == 1) {
                        sec = [DateSomeThing getStringWithCurrentTimeStr:model.endtime currentDateFormat:@"HH:mm:ss"];
                    } else if (model.state == 0) {
                        sec = [DateSomeThing getStringWithCurrentTimeStr:model.sktime currentDateFormat:@"HH:mm:ss"];
                    }
                    [self.timeView setTimerForReset:sec];
                    self.timerSec = sec;
                    
                    _page = 1;
                    [self getGoodsNetData];
                }];
                _page = 1;
                [blockSelf getGoodsNetData];
            }
        } else {
            [MBProgressHUD showError:blockSelf.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
        [MBProgressHUD showError:blockSelf.view title:@"" code:@"" animated:YES];
    }];
}
- (void)endRefreshing {
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
}
- (void)getNetFailure {
    if (_page != 1) {
        _page--;
    }
}
- (void)getNetSuccess:(NSDictionary *)dics {
    [self.tableView.mj_footer setHidden:YES];
    
    if ([dics[@"data"][@"totalRow"] integerValue] > self.tableArray.count) {
        [self.tableView.mj_footer setHidden:NO];
    } else {
        [self.tableView.mj_footer setHidden:YES];
    }
    
    if (self.page == 1) {
        [self.tableArray removeAllObjects];
        [self.tableView.mj_footer resetNoMoreData];
    }
    // 数据列表
    NSArray *list = dics[@"data"][@"list"];
    if (list.count == 0 && self.page != 1) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
        [self getNetFailure];
        return;
    }
    for (NSDictionary *dic in list) {
        GoodsListModel *model = [GoodsListModel mj_objectWithKeyValues:dic];
        [self.tableArray addObject:model];
    }
    [self.tableView reloadData];
}
- (void)getGoodsNetData {
    //[MBProgressHUD showHUDProgress:self.view animated:YES];

    NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
    TimeUpTimeItem *item = self.timeArr[self.titleView.selectIndex];
    [parameters setObject:item.skid forKey:@"skid"];
    [parameters setObject:@(self.page) forKey:@"pageNumber"];
    [parameters setObject:PageSize forKey:@"pageSize"];
    
    __block typeof(self) blockSelf = self;
    [MYAFNetworking POST:URL_Get_Seckill_Goods_List parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
        [blockSelf endRefreshing];
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            NSDictionary *dic = responseObject;
            [blockSelf getNetSuccess:dic];
        } else {
            [blockSelf getNetFailure];
            [MBProgressHUD showError:blockSelf.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [blockSelf getNetFailure];
        [blockSelf endRefreshing];
        [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
        [MBProgressHUD showError:blockSelf.view title:@"" code:@"" animated:YES];
    }];
}
- (void)countdownTimerAction {
    self.timerSec--;
    if (self.timerSec <= 0) {
        [self.timer invalidate];
        self.timer = nil;
        [self getNetData];
    }
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.tableArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TimeUpItemCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    GoodsListModel *model = self.tableArray[indexPath.row];
    
    [cell.iconImageView sd_setImageWithURL:GetUrl(model.gimg) placeholderImage:PlaceholderImageSmall changeContentModel:UIViewContentModeScaleAspectFill];
    cell.nameLabel.text = model.gname;
    
    NSString *tempStr = TextIsNotNil(model.gseckillprice)?model.gseckillprice:@"0";
    NSString *price = [NSString stringWithFormat:@"¥%@",tempStr];
    NSMutableAttributedString *priceAttStr = [[NSMutableAttributedString alloc] initWithString:price];
    [priceAttStr setAttributes:@{NSFontAttributeName:TextPingFangMediumFontSize(14)} range:NSMakeRange(0, price.length)];
    [priceAttStr setAttributes:@{NSFontAttributeName:TextPingFangMediumFontSize(20)} range:[price rangeOfString:tempStr]];
    [cell.priceLabel setAttributedText:priceAttStr];
    
    cell.oldPriceLabel.text = [NSString stringWithFormat:@"¥%@",model.goldprice];
    cell.oldLabel.text = @"原价";
    // 是否正在秒杀 传入-当前
    TimeUpTimeItem *item = self.timeArr[self.titleView.selectIndex];
    if (item.state == 1) {
        // 抢购中
        [cell.buyButton setTitle:@"去抢购" forState:UIControlStateNormal];
        cell.buyButton.backgroundColor = [UIColor redF2color];
    } else if (item.state == 0) {
        // 未开始
        [cell.buyButton setTitle:@"未开始" forState:UIControlStateNormal];
        cell.buyButton.backgroundColor = [UIColor grayTextColor];
    } else if (item.state == -1) {
        // 已结束
        [cell.buyButton setTitle:@"已结束" forState:UIControlStateNormal];
        cell.buyButton.backgroundColor = [UIColor grayTextColor];
    }
    
    __block typeof(self) blockSelf = self;
    cell.block = ^{
        if (!model.isshelves) {
            [MBProgressHUD showError:blockSelf.view title:@"该商品已下架" code:@"" animated:YES];
            return;
        }
        GoodsDetailViewController *detailVC = [[GoodsDetailViewController alloc] init];
        if (blockSelf.timeArr.count > 0) {
            TimeUpTimeItem *item = blockSelf.timeArr[blockSelf.titleView.selectIndex];
            if (item.state == 1) {
                detailVC.type = GoodsDetailViewControllerTypeForFlashSale;
            } else if (item.state == 0 || item.state == -1) {
                detailVC.type = GoodsDetailViewControllerTypeForNormal;
            }
        }
        detailVC.gid = model.gid;
        [blockSelf.navigationController pushViewController:detailVC animated:YES];
    };
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 130;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    GoodsListModel *model = self.tableArray[indexPath.row];
    if (!model.isshelves) {
        [MBProgressHUD showError:self.view title:@"该商品已下架" code:@"" animated:YES];
        return;
    }
    GoodsDetailViewController *detailVC = [[GoodsDetailViewController alloc] init];
    if (self.timeArr.count > 0) {
        TimeUpTimeItem *item = self.timeArr[self.titleView.selectIndex];
        if (item.state == 1) {
            detailVC.type = GoodsDetailViewControllerTypeForFlashSale;
        } else if (item.state == 0 || item.state == -1) {
            detailVC.type = GoodsDetailViewControllerTypeForNormal;
        }
    }
    detailVC.gid = model.gid;
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.width, 30)];
    view.backgroundColor = [UIColor grayfaColor];
    [view addSubview:self.timeView];
    self.timeView.frame = CGRectMake(ScreenWidth - 13 * 6, 6, 11 * 6, 18);
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, view.width * 0.5, view.height)];
    label.font = TextPingFangFontSize(12);
    label.textColor = [UIColor blackTextColor];
    
    UILabel *lastLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.timeView.left - 40, 0, 40, view.height)];
    lastLabel.font = TextPingFangFontSize(12);
    lastLabel.textColor = [UIColor gray66Color];
    
    NSString *labelStr = @"", *lastLabelStr = @"";
    if (self.timeArr.count > 0) {
        TimeUpTimeItem *item = self.timeArr[self.titleView.selectIndex];
        if (item.state == 1) {
            labelStr = @"抢购中 先下单先得哦！";
            lastLabelStr = @"距结束";
        } else if (item.state == 0) {
            labelStr = @"即将开始 先下单先得哦！";
            lastLabelStr = @"距开始";
        }
    }
    label.text = labelStr;
    lastLabel.text = lastLabelStr;
    
    
    UIView *topLine = [[UIView alloc] initWithFrame:CGRectMake(0, 0, view.width, 1)];
    topLine.backgroundColor = [UIColor grayE5Color];
    
    UIView *bottomLine = [[UIView alloc] initWithFrame:CGRectMake(0, view.height - 1, view.width, 1)];
    bottomLine.backgroundColor = [UIColor grayE5Color];
    
    [view addSubview:label];
    [view addSubview:lastLabel];
    
    [view addSubview:topLine];
    [view addSubview:bottomLine];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30;
}
#pragma mark - DZNEmptyDataSetSource, DZNEmptyDataSetDelegate
//主提示标题
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    return [[NSAttributedString alloc] initWithString:@"暂无秒杀商品"
                                           attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:16.0],
                                                        NSForegroundColorAttributeName:[UIColor grayTextColor]}];
}
- (void)emptyDataSet:(UIScrollView *)scrollView didTapView:(UIView *)view {
    _page = 1;
    [self getNetData];
}

#pragma mark - Getters
- (NSMutableArray<TimeUpTimeItem *> *)timeArr {
    if (!_timeArr) {
        _timeArr = [[NSMutableArray alloc] init];
    }
    return _timeArr;
}
- (NSMutableArray<GoodsListModel *> *)tableArray {
    if (!_tableArray) {
        _tableArray = [[NSMutableArray alloc] init];
    }
    return _tableArray;
}
- (TimeUpTitleView *)titleView {
    if (!_titleView) {
        _titleView = [[TimeUpTitleView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 50)];
    }
    return _titleView;
}

- (TimeClockView *)timeView {
    if (!_timeView) {
        _timeView = [[TimeClockView alloc] initWithCornerRadius:4];
    }
    return _timeView;
}

- (void)dealloc {
    [self.timer invalidate];
    self.timer = nil;
}

@end
